#!/usr/bin/env python
# encoding: utf-8
"""
Copyright 2011, 2012 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import tvod.util as tvod_util
import tvod.package as tvod_package
import os, time, logging, threading, Queue

class Error(Exception):
	pass
	
class PackageProcessor:
	def __init__(self,scriptpath):
		self.basepath = os.path.join(os.path.dirname(scriptpath),"..","lib")
		self.library = tvod_package.Library(self.basepath,"TVOD3") # default library is TVOD3
		self.terminate = False
		self.workers = 5
	def start(self,watchfolders):
		self.terminate = False
		# create the pipeline of items to be processed
		queue = Queue.Queue()
		# create Threadable process objects
		processes = [ ]
		for folder in watchfolders:
			processes.append(tvod_util.XMLWatchFolder(folder,queue))
		for worker_number in range(0,self.workers):
			processes.append(PackageProcessor.Worker(queue,self.library,worker_number+1))
		# create threads for processes
		for process in processes:
			t = threading.Thread(name=process.name,target=process.runloop)
			logging.debug("Created thread %s" % t)
			t.daemon = True
			t.start()
		# wait until the terminate flag is set
		while not self.terminate:
			# wait in the main thread for termination condition
			time.sleep(1)
		# signal each process to terminate
		for process in processes:
			process.exit = True
		logging.debug("Signalled all processes to exit")
	def stop(self):
		logging.info("Terminating application")
		self.terminate = True
	
	class Worker(tvod_util.Worker):
		def __init__(self,queue,library,worker_number=0):
			assert isinstance(library,tvod_package.Library)
			tvod_util.Worker.__init__(self,queue,worker_number)
			self._library = library
		def process(self,item):
			assert isinstance(item,tvod_util.WorkerItem)
			try:
				# create a package from a WorkerItem
				package = tvod_package.Package(item.path,self._library)
				# what is the package name
				logging.info("%s: Processing %s" % (self.name,package.name))
				# do work
				package.validate()
				time.sleep(10)
				# finished processing
				logging.info("%s: Finished" % self.name)
			except tvod_util.PackageError, e:
				# TODO
			except Error, e:
				logging.error("%s: Unable to process: %s: %s" % (self.name,item,e))
	
